import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from "@/api";
const state = {
  cartList: [],
};
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList;
  },
};
const actions = {
  async getCartList({ commit }) {
    let result = await reqCartList();
    if (result.code == 200) {
      commit("GETCARTLIST", result.data);
    }
  },
  //删除购物车的产品
  async deleteCartListBySkuId({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("failed"));
    }
  },
  //修改购物车是否选中
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("failed"));
    }
  },
  //删除全部勾选的商品
  deleteAllCheckedCart({ dispatch, getters }) {
    let promiseAll = [];
    getters.cartList.cartInfoList.forEach((element) => {
      let promise =
        element.isChecked == 1
          ? dispatch("deleteCartListBySkuId", element.skuId)
          : "";
      promiseAll.push(promise);
    });
    return Promise.all(promiseAll);
  },
  //修改全选状态
  updateAllCartIsChecked({ dispatch, state }, isChecked) {
    let promiseAll = [];
    state.cartList[0].cartInfoList.forEach((element) => {
      if (element.isChecked != isChecked) {
        let promise = dispatch("updateCheckedById", {
          skuId: element.skuId,
          isChecked,
        });
        promiseAll.push(promise);
      }
    });
    return Promise.all(promiseAll);
  },
};
const getters = {
  cartList(state) {
    return state.cartList[0] || {};
  },
};
export default {
  state,
  mutations,
  actions,
  getters,
};
